package com.qyer.commons.param;

import static com.qyer.commons.model.User.buildUser;
import static com.qyer.commons.utils.CommonUtils.cast2String;
import static com.qyer.commons.utils.GenericConstants.MAX_CONTEXT_LENGTH;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.qyer.commons.exception.ParameterException;
import com.qyer.commons.model.User;
import com.qyer.commons.utils.CommonUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * User: Z J Wu Date: 2016/04/11 Time: 17:58 Package: com.qyer.commons.param
 */
public abstract class HttpParameter {

  @JsonIgnore
  protected User user;

  @JsonIgnore
  protected String context;

  @JsonIgnore
  protected String requestId;

  public HttpParameter(User user, String context, String requestId) throws ParameterException {
    if (StringUtils.isEmpty(context)) {
      throw new ParameterException("context is null");
    }
    if (context.length() >= MAX_CONTEXT_LENGTH) {
      this.context = context.substring(0, MAX_CONTEXT_LENGTH);
    } else {
      this.context = context;
    }
    this.user = user;
    this.requestId = requestId;
  }

  public HttpParameter(HttpServletRequest req) throws ParameterException {
    this(buildUser(req), cast2String(req.getParameter("context")), CommonUtils.getRequestId());
  }

  public User getUser() {
    return user;
  }

  public void setUser(User user) {
    this.user = user;
  }

  public String getContext() {
    return context;
  }

  public void setContext(String context) {
    this.context = context;
  }

  public String getRequestId() {
    return requestId;
  }

  public void setRequestId(String requestId) {
    this.requestId = requestId;
  }
}
